<?php
	require_once(dirname(dirname(dirname(dirname(__FILE__)))) . "/engine/start.php");
	
	$basesec = get_plugin_setting("chatUpdateInterval","elggchat");
	if(!$basesec) $basesec = 5;
	$maxsecs = get_plugin_setting("maxChatUpdateInterval","elggchat");
	if(!$maxsecs) $maxsecs = 30;
?>

	var secs
	var basesec = <?php echo $basesec;?>;
	var maxsecs = <?php echo $maxsecs;?>;
	var timerID = null
	var timerRunning = false
	var delay = 1000
	var lastTimeDataReceived = new Date().getTime();
	
	function InitializeTimer(){
		
		// Set the length of the timer, in seconds
		secs = basesec;
		StopTheClock();
		StartTheTimer();
	}

	function StopTheClock(){
		if(timerRunning)
			clearTimeout(timerID)
		timerRunning = false;
	}

	function StartTheTimer(){
		if (secs==0){
			checkForSessions();
			refreshChat();
		} else {
			secs = secs - 1;
			timerRunning = true;
			timerID = self.setTimeout("StartTheTimer()", delay);
		}
	}
	
	function sendMessage(sessionid){
		
		StopTheClock();
		if($("div[name='chat_window'][rel='" + sessionid +"'] textarea").val()){
			$.post("<?php echo $CONFIG->wwwroot; ?>action/elggchat/post_message", $("div[name='chat_window'][rel='" + sessionid +"'] #chat_input").serialize() , function(data){
				refreshChat();
				$("div[name='chat_window'][rel='" + sessionid +"'] textarea").val("").focus();
			});
		}
	}
	
	function refreshChat(){
		
		StopTheClock();
		
		$("div[name='chat_window']").each(function(){
			
			var sessionid = this.getAttribute('rel');
			
			var postdata = $("div[name='chat_window'][rel='" + sessionid +"'] #chat_input").serialize() + "&offset=" + $("div[name='chat_window'][rel='" + sessionid +"'] #chat_data div[name='message']:last").attr('id');
			
			$.post("<?php echo $CONFIG->wwwroot; ?>action/elggchat/poll", postdata, function(data){
				if(data){
					$("div[name='chat_window'][rel='" + sessionid +"'] #chat_data").append(data);

					resize_chat(sessionid);
					// record last time data received
					lastTimeDataReceived = new Date().getTime();

					//window.focus();
					//newExcitingAlerts();
				} 
			});
		});
		
		// if needed apply multiplier
		var currentTimeStamp = new Date().getTime();
		var timeDiff = (currentTimeStamp - lastTimeDataReceived) / 1000;
		
		var interval = Math.ceil((Math.sqrt(Math.pow(basesec * 10 / 2, 2) + (2 * basesec * 10 * timeDiff)) - (basesec * 10 / 2)) / (basesec * 10));
		// reset secs
		secs = basesec * interval;
		if(secs > maxsecs){
			secs = maxsecs;
		}
		StartTheTimer();
	}
	
	function toggleFriendsPicker(){
		$.post('<?php echo $CONFIG->wwwroot;?>action/elggchat/friends_picker', function(data){
			$("#elggchat_friends_picker").html(data);
			$("#elggchat_friends_picker").slideToggle();
		});
	}
	
	function ifEnter(field,event, sessionid) {
		var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		shift = event.shiftKey;
		
		if (theCode == 13 && !shift){
			sendMessage(sessionid);
			return false;
		} else {
			return true;
		}
	} 
	
	function joinSession(sessionid){
		StopTheClock();
		var chat_window = $("div[name='chat_window'][rel='" + sessionid +"']");
		
		if(chat_window.length == 0){
			$.post("<?php echo $CONFIG->wwwroot;?>mod/elggchat/chat.php?chatsession=" + sessionid, function(data){
				if(data){
					$("#elggchat_windows").append("<div class='elggchat_window' name='chat_window' rel='" + sessionid  + "'>" + data  + "</div>");
					
					chat_window = $("div[name='chat_window'][rel='" + sessionid +"']");
					chat_window.dialog({ 
						minHeight: 300, 
						height: 500,
						title: $('#elggchat_sessions div[rel="' + sessionid + '"]').html(), 					
						resizeStop: function(event, ui) { 
										resize_chat(sessionid);
									},
						close: function(event, ui) {
										$('#elggchat_sessions div[rel="' + sessionid + '"]').toggleClass('elggchat_session_active'); 
									}
					});
					refreshChat();
				}
				resize_chat(sessionid);
				chat_window.find("textarea").focus();
				$('#elggchat_sessions div[rel="' + sessionid + '"]').toggleClass('elggchat_session_active');
			});
		} else {
			if(chat_window.dialog('isOpen')){
				chat_window.dialog('close');
			} else {
				chat_window.dialog('open');
				$('#elggchat_sessions div[rel="' + sessionid + '"]').toggleClass('elggchat_session_active');	
			}			
		}
		resize_chat(sessionid);
		chat_window.find("textarea").focus();
	}

	function startSession(friendGUID){
		$.post('<?php echo $CONFIG->wwwroot;?>action/elggchat/create?invite=' + friendGUID, function(data){
			if(data){
				checkForSessions(data);
			}
		});
	}
	
	function inviteFriends(sessionid){
		var chat_window = $("div[name='chat_window'][rel='" + sessionid +"']");
		
		if(chat_window.find('#chat_friends').css("display") == "none"){
			chat_window.find('#chat_divs > div').hide();
			chat_window.find('#chat_loading').show();
			
			$.post('<?php echo $CONFIG->wwwroot;?>action/elggchat/invite_friends?chatsession=' + sessionid, function(data){
				
				chat_window.find('#chat_friends').html(data).show();
				chat_window.find('#chat_loading').hide();
			});
		} else {
			showChat(sessionid)
			chat_window.find('#chat_friends').html("");
		}
	}
	
	function showSessionInfo(sessionid){
		var chat_window = $("div[name='chat_window'][rel='" + sessionid +"']");
		
		if(chat_window.find('#chat_info').css("display") == "none"){
			chat_window.find('#chat_divs > div').hide();
			chat_window.find('#chat_loading').show();
			
			$.post('<?php echo $CONFIG->wwwroot;?>action/elggchat/session_info?chatsession=' + sessionid, function(data){
				
				chat_window.find('#chat_info').html(data).show();
				chat_window.find('#chat_loading').hide();
			});
		} else {
			showChat(sessionid);
			chat_window.find('#chat_info').html("");
		}
	}
	
	function showChat(sessionid){
		$('div[name="chat_window"][rel="' + sessionid + '"] #chat_divs > div').hide();
		$('div[name="chat_window"][rel="' + sessionid + '"] #chat_messages').show();
		resize_chat(sessionid);
	}
	
	function leaveSession(sessionid){
		if(confirm("<?php echo elgg_echo('elggchat:chat:leave:confirm');?>")){
			
			$.post("<?php echo $CONFIG->wwwroot; ?>action/elggchat/leave?chatsession=" + sessionid, function(){
				$('div[name="chat_window"][rel="' + sessionid + '"]').dialog('close');
				checkForSessions();
			});
			
		} 
	}
	
	function elggchat_toolbar_resize(){
		$("#elggchat_toolbar_left").css("width", $(document).width() - $("#toggle_elggchat_toolbar").width());
	}
	
	function toggleChatToolbar(){
		$('#toggle_elggchat_toolbar').toggleClass('minimizedToolbar');
		$('#elggchat_toolbar_left').toggle('slide', null, 'slow');	
	}
	
	function resize_chat(sessionid){
		var chat_window = $("div[name='chat_window'][rel='" + sessionid +"']");
		var window_height = chat_window.height();
		var menu_height = chat_window.find("#chat_menu").height();
		var input_height = chat_window.find("#chat_input").height() ;
		
		var newHeight = window_height - menu_height - input_height;
		chat_window.find("#chat_data").css("height", newHeight);
		// make sure to scroll to bottom
		var scrHeight = chat_window.find("#chat_data").attr("scrollHeight");
		chat_window.find("#chat_data").attr("scrollTop", scrHeight);
	}
	
	function checkForSessions(newSessionID){
		
		
		var activeSessions = [];
		$(".elggchat_session_active").each(function(){
			activeSessions.push(this.getAttribute('rel'));
		});
		
		$.post("<?php echo $CONFIG->wwwroot; ?>action/elggchat/session_check", function(data){
			if(data){
				
				$("#elggchat_toolbar_left").html(data);
				
				$.map(activeSessions,
					function(x, idx){
						$('#elggchat_sessions div[rel="' + x + '"]').toggleClass('elggchat_session_active');
						var newTitle = $('#elggchat_sessions div[rel="' + x + '"]').html();
						$('div[name=chat_window][rel="' + x + '"]').dialog('option', 'title', newTitle);	
					}
				);
				elggchat_toolbar_resize();
				if(newSessionID > 0){
					
					joinSession(parseInt(newSessionID));
				}
			} else {
				$("#elggchat_sessions").html("");
				elggchat_toolbar_resize();
			}			
		});
	}
	
	$(document).ready(function(){
		
		$("#elggchat_toolbar").fadeIn(2000);
		$(window).resize(function(){
			elggchat_toolbar_resize();
		});
		InitializeTimer();
		checkForSessions();	
	});
	